/* © 2020-2025 ALYR.NET */
// Vue.js 应用主文件
const { createApp } = Vue;

createApp({
    data() {
        return {
            files: [],
            results: [],
            isAnalyzing: false,
            isLogoRecognition: false,
            isDragOver: false,
            isPasteActive: false,
            showWelcomeModal: false,
            showResults: false
        };
    },
    
    mounted() {
        // 监听全局粘贴事件
        document.addEventListener('paste', this.handlePaste);
        
        // 监听全局拖拽事件
        document.addEventListener('dragover', this.handleDragOver);
        document.addEventListener('drop', this.handleDrop);
        document.addEventListener('dragleave', this.handleDragLeave);
    },
    
    beforeUnmount() {
        // 清理事件监听器
        document.removeEventListener('paste', this.handlePaste);
        document.removeEventListener('dragover', this.handleDragOver);
        document.removeEventListener('drop', this.handleDrop);
        document.removeEventListener('dragleave', this.handleDragLeave);
    },
    
    methods: {
        triggerFileInput() {
            this.$refs.fileInput.click();
        },
        
        handleFileSelect(event) {
            const files = Array.from(event.target.files);
            this.addFiles(files);
        },
        
        handleDragOver(event) {
            event.preventDefault();
            this.isDragOver = true;
        },
        
        handleDragLeave(event) {
            // 只有当拖拽离开整个窗口时才设置为false
            if (event.clientX === 0 && event.clientY === 0) {
                this.isDragOver = false;
            }
        },
        
        handleDrop(event) {
            event.preventDefault();
            this.isDragOver = false;
            
            const files = Array.from(event.dataTransfer.files);
            this.addFiles(files);
        },
        
        handlePaste(event) {
            const items = event.clipboardData.items;
            const files = [];
            
            for (let item of items) {
                if (item.type.startsWith('image/')) {
                    const file = item.getAsFile();
                    if (file) {
                        files.push(file);
                    }
                }
            }
            
            if (files.length > 0) {
                this.addFiles(files);
                this.isPasteActive = true;
                setTimeout(() => {
                    this.isPasteActive = false;
                }, 1000);
            }
        },
        
        addFiles(newFiles) {
            for (let file of newFiles) {
                // 验证文件类型
                if (!file.type.startsWith('image/')) {
                    alert(`文件 ${file.name} 不是图片格式！`);
                    continue;
                }
                
                // 验证文件大小 (10MB)
                if (file.size > 10 * 1024 * 1024) {
                    alert(`文件 ${file.name} 大小超过10MB！`);
                    continue;
                }
                
                // 检查是否已存在
                const exists = this.files.some(f => f.name === file.name && f.size === file.size);
                if (exists) {
                    continue;
                }
                
                // 创建预览URL
                const reader = new FileReader();
                reader.onload = (e) => {
                    const fileObj = {
                        file: file,
                        name: file.name,
                        size: file.size,
                        preview: e.target.result,
                        status: 'pending'
                    };
                    this.files.push(fileObj);
                };
                reader.readAsDataURL(file);
            }
        },
        
        removeFile(index) {
            this.files.splice(index, 1);
            // 同时移除对应的结果
            if (this.results[index]) {
                this.results.splice(index, 1);
            }
        },
        
        clearAll() {
            this.files = [];
            this.results = [];
            this.showResults = false;
        },
        
        async analyzeAll() {
            this.analyzeFiles('content');
        },
        
        async analyzeFiles(analysisType = 'content') {
            if (this.files.length === 0) {
                alert('请先选择图片！');
                return;
            }
            
            this.isAnalyzing = true;
            this.showResults = true;
            if (analysisType === 'logo') {
                this.isLogoRecognition = true;
            } else {
                this.isLogoRecognition = false;
            }
            this.results = [];
            
            for (let i = 0; i < this.files.length; i++) {
                this.files[i].status = 'analyzing';
                
                try {
                    const formData = new FormData();
                    formData.append('image', this.files[i].file);
                    formData.append('analysis_type', analysisType);
                    
                    const response = await axios.post('api/analyze.php', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    });
                    
                    // 调试：记录完整的LOGO识别结果
                    if (analysisType === 'logo') {
                        console.log('LOGO识别API响应:', response.data);
                    }
                    
                    const result = {
                        ...response.data,
                        filename: this.files[i].name,
                        preview: this.files[i].preview
                    };
                    
                    // 如果是LOGO识别且有品牌信息，处理品牌显示名称
                    if (analysisType === 'logo' && result.logoInfo && result.logoInfo.brand) {
                        console.log('处理品牌:', result.logoInfo.brand, '置信度:', result.logoInfo.confidence);
                        // 异步处理品牌显示名称
                        this.getBrandDisplayName(result.logoInfo.brand).then(displayName => {
                            result.logoInfo.displayName = displayName;
                            result.logoInfo.englishName = this.getBrandEnglishName(result.logoInfo.brand);
                            // 触发视图更新
                            this.$forceUpdate();
                        });
                    }
                    
                    this.results.push(result);
                    this.files[i].status = result.status;
                    
                } catch (error) {
                    console.error('分析失败:', error);
                    const errorResult = {
                        status: 'error',
                        message: '分析失败: ' + (error.response?.data?.message || error.message),
                        filename: this.files[i].name,
                        preview: this.files[i].preview
                    };
                    
                    this.results.push(errorResult);
                    this.files[i].status = 'error';
                }
                
                // 添加小延迟避免请求过快
                await new Promise(resolve => setTimeout(resolve, 200));
            }
            
            this.isAnalyzing = false;
        },
        
        formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
        },
        
        getStatusClass(status) {
            return `status-${status}`;
        },
        
        getStatusText(status) {
            const statusMap = {
                'pending': '待分析',
                'analyzing': '分析中',
                'safe': '仅代表当前分析的图片没有违规！',
                'unsafe': '违规',
                'warning': '警告',
                'error': '错误',
                'logo_detected': '检测到LOGO',
                'no_logo': '未检测到LOGO',
                'low_confidence': '置信度较低'
            };
            return statusMap[status] || '未知';
        },
        
        getStatusColor(status) {
            const colorMap = {
                'safe': '#27ae60',
                'unsafe': '#e74c3c',
                'warning': '#f39c12',
                'error': '#e74c3c',
                'logo_detected': '#3498db',
                'no_logo': '#e74c3c'
            };
            return colorMap[status] || '#7f8c8d';
        },
        
        getStatusIcon(status) {
            const iconMap = {
                'safe': '✅',
                'unsafe': '❌',
                'warning': '⚠️',
                'error': '❌',
                'logo_detected': '✅',
                'no_logo': '❌'
            };
            return iconMap[status] || '❓';
        },
        
        getStatCount(status) {
            return this.results.filter(r => r.status === status).length;
        },
        
        closeWelcomeModal() {
            this.showWelcomeModal = false;
        },
        
        openInNewWindow() {
            window.open(window.location.href, '_blank');
        },
        
        logoRecognition() {
            if (this.files.length === 0) {
                alert('请先上传图片文件');
                return;
            }
            this.isAnalyzing = true;
            this.isLogoRecognition = true;
            this.showResults = true;
            this.results = [];
            
            // 使用百度云LOGO识别API
            this.analyzeFiles('logo');
        },
        
        // 检测是否为中文字符
        isChinese(text) {
            return /[\u4e00-\u9fff]/.test(text);
        },
        
        // 机器实时翻译（使用翻译API）
        async translateToEnglish(chineseText) {
            // 使用机器翻译API进行实时翻译
            try {
                const response = await this.simpleTranslate(chineseText);
                return response || chineseText;
            } catch (error) {
                console.log('翻译失败，保持原文:', error);
                return chineseText;
            }
        },
        
        // 简单翻译函数（可替换为真正的翻译API）
        async simpleTranslate(text) {
            // 这里可以调用真正的翻译API
            // 目前返回原文作为fallback
            return text;
        },
        
        async getBrandDisplayName(brand) {
            // 调试：记录接收到的品牌名称
            console.log('前端接收到的品牌名称:', brand);
            
            // 直接返回原始品牌名称，不进行翻译
            return brand;
        },
        
        async getBrandEnglishName(brand) {
            // 使用机器翻译获取英文名称
            if (this.isChinese(brand)) {
                return await this.translateToEnglish(brand);
            }
            return brand;
        },
        
        async openPngLogo(brand) {
            // 获取英文品牌名用于搜索
            const keyword = await this.getBrandEnglishName(brand);
            const url = `https://www.pngitem.com/so/${encodeURIComponent(keyword)}-LOGO/`;
            window.open(url, '_blank');
        },
        
        openBaiduPng(brand) {
            // 使用品牌名（中文或英文都可以）进行百度图片搜索
            const keyword = encodeURIComponent(brand);
            const url = `https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=&st=-1&fm=index&fr=&hs=0&xthttps=111110&sf=1&fmq=&pv=&nc=1&z=7&se=&showtab=0&fb=0&face=0&istype=2&ie=utf-8&word=${keyword}%2Blogo%2Bpng`;
            window.open(url, '_blank');
        },
        
        openFontSearch(brand) {
            // 打开百度AI创造页面
            const brandName = brand || '品牌';
            const prompt = encodeURIComponent(`请生成[${brandName}]官方LOGO的完全复刻版，使用标准色，1:1比例透明背景PNG，4K分辨率，要求100%精确还原原始设计，禁止任何修改或艺术加工`);
            const url = `https://image.baidu.com/front/aigc?atn=aigc&fr=home&imgcontent=%7B"aigcQuery"%3A"${prompt}"%2C"imageAigcId"%3A"4199096378"%7D&isImmersive=1&pd=image_content&tn=aigc&top=%7B"sfhs"%3A1%7D&ratio=3%3A4&sa=searchpromo_shijian_photohp_create&word=${prompt}`;
            window.open(url, '_blank');
        },
        
        openCompanyQuery(brand) {
            // 打开爱企查企业查询页面
            const keyword = encodeURIComponent(brand);
            const url = `https://aiqicha.baidu.com/advertising?q=${keyword}`;
            window.open(url, '_blank');
        }
    }
}).mount('#app');